package com.tozed.android.launcher.simpleui;

import java.util.ArrayList;
import java.util.Locale;

import com.tozed.android.launcher.LauncherApplication;
import com.tozed.android.launcher.R;

import android.app.ActionBar;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.text.TextUtils;

public class SimpleFolder extends Activity implements View.OnClickListener, SimpleLauncherModel.FolderCallbacks 
	,SimplePageIndicator.NaviPointLayoutChange, View.OnLongClickListener
{
	public static final String TAG = "SimpleFolder ";
	private static final boolean DEBUG = true;
	public static final String CLASS_NAME = SimpleFolder.class.getName();
	
	private static final String NEED_TO_RELOAD = "SimpleFolder.need_to_be_re-loaded";
	public static final int REMOVE_OUT_LINE_DELAY = 50;
	public static final int REMOVE_OUT_LINE_MESSAGE = 5000;
	public static final String SYSTEM_FOLDER_NAME = "str_other_apps";
	public static final int UNREAD_NUM_UPDATE = 2;
	private ActionBar mActionBar;
	private View mClickView;
	private LayoutInflater mInflater;
	private boolean mIsSystemFolder;
	private String mLocaleLanguage = Locale.getDefault().getLanguage();
	private SimpleWorkspace mSimpleFolderWorkspace;
	private SimplePageIndicator mSimpleQuickNavigation;
	private TextView mTextView;
	private int screenCount = 0;
	private static boolean mIsFirstCreate = false;
	
	// 是其它app文件夹或者下载app文件夹对应的app集合
	private ArrayList<SimpleApplicationInfo> mContentApps = new ArrayList<SimpleApplicationInfo>();
	
	// 外部Intent传递参数
	private String mFolderName = null;
	
	private final Handler mHandler = new Handler()
	{
		public void handleMessage(Message msg)
		{
			if (msg.what == REMOVE_OUT_LINE_MESSAGE && mClickView != null && mClickView instanceof SimpleBubbleTextView)
			{
				SimpleBubbleTextView bubbleTextView = (SimpleBubbleTextView)mClickView;
				bubbleTextView.setPressed(false);
				bubbleTextView.invalidate();
			}
			
			SimpleApplicationInfo app;
			
			if (msg.what == UNREAD_NUM_UPDATE && msg.obj instanceof SimpleApplicationInfo)
			{
				app = (SimpleApplicationInfo) msg.obj;
				SimpleCellLayout cellLayout = (SimpleCellLayout)mSimpleFolderWorkspace.getChildAt(app.screen);
				
				if (cellLayout == null){
					Log.w(TAG, "SimpleFolder layout " + app.screen + " is not exist when udapte unRead childcount="
							+ mSimpleFolderWorkspace.getChildCount());
					return;
				}
				
				View cellView = cellLayout.getChildAt(app.cellX, app.cellY);
				
				if (DEBUG)
					Log.i(TAG, "SimpleFolder update unRead in folder item screen=" + app.screen
							+ " cellX=" + app.cellX + " cellY=" + app.cellY + " unReadNum=" + app.getUnReadNum());
				
				if (cellView == null || !(cellView instanceof SimpleBubbleTextView)){
					Log.w(TAG, "SimpleFolder not found " + app.getClsName() + " view when update UnReadNum");
					return;
				}
				
				SimpleBubbleTextView bubbleTextView = (SimpleBubbleTextView)cellView;
				bubbleTextView.setUnreadMarkable(true);
				bubbleTextView.setUnreadNum(app.getUnReadNum());
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		mActionBar = getActionBar();
	    setContentView(R.layout.simple_folder);
	    
	    mActionBar.setDisplayHomeAsUpEnabled(true);
	    
	    String strFolderName = (String)getIntent().getExtra("folderName");
	    
	    int resId = getResources().getIdentifier(SYSTEM_FOLDER_NAME, "string", "com.tozed.android.launcher");
	    String folderNameRes = getResources().getString(resId, new Object[] { "string", "com.tozed.android.launcher" });
	    
	    if (strFolderName != null)
	    {
	      mActionBar.setTitle(strFolderName);
	      mFolderName = strFolderName;
	      if (strFolderName.equals(folderNameRes))
	        mIsSystemFolder = true;
	    }else{
	    	mActionBar.setTitle(folderNameRes);
	    }
	    
	     mInflater = getLayoutInflater();
	    ((LauncherApplication)getApplication()).setSimpleFolder(this);
	    restoreState(savedInstanceState);
	    
	    setUpViews();
	    
	    SimpleUILauncher.setFolderActiviytHanlder(mHandler);
	}
	
	private void restoreState(Bundle bundle)
	{
		if (bundle != null && bundle.getBoolean("SimpleFolder.need_to_be_re-loaded"))
		{
			((LauncherApplication)getApplication()).getSimpleIconCache().flush();
			
			for (SimpleApplicationInfo appDownload : SimpleLauncherModel.sDownloadApps){
				appDownload.mIcon = null;
			}
			
			for (SimpleApplicationInfo appOther: SimpleLauncherModel.sOtherApps){
				appOther.mIcon = null;
			}
		}
	}

	private void setUpViews(){
		setContentApps();
		
	    mSimpleFolderWorkspace = ((SimpleWorkspace)findViewById(R.id.simple_workspace_folder));
	    mSimpleQuickNavigation = ((SimplePageIndicator)findViewById(R.id.simple_folder_divider));
	    mTextView = ((TextView)findViewById(R.id.text_no_download));
	    mSimpleQuickNavigation.setSimpleFolder(this);
	    
	    SimpleLauncherModel.sortAndArrangeFolderApps(mContentApps);
	    removeAndAddApps();
	    
	    if (screenCount <= 1)
	    	mSimpleQuickNavigation.setVisibility(View.GONE);
	    else
	    	mSimpleQuickNavigation.setVisibility(View.VISIBLE);
	    
		updateDividerLayout();
		mSimpleFolderWorkspace.requestLayout();
	}
	
	private void updateDividerLayout()
	{
		//int navBarSize = getResources().getDimensionPixelSize(R.dimen.simple_navigation_bar_size);
		//FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams)mSimpleQuickNavigation.getLayoutParams();
		//lp.bottomMargin += navBarSize/2;
		mSimpleQuickNavigation.requestLayout();
	}
	
	@Override
	protected void onStart()
	{
		if (!mIsFirstCreate){
			overridePendingTransition(R.anim.activity_close_enter, R.anim.activity_close_exit);
		}
		
		super.onStart();
	}
	
	@Override
	protected void onResume()
	{
		if (mContentApps.size() == 0 && mTextView != null && mTextView.getVisibility() != View.VISIBLE)
			mTextView.setVisibility(View.VISIBLE);
		
		SimpleUtilities.sendAccessibilityEvent(mFolderName);
		super.onResume();
	}
	
	@Override
	protected void onPause(){
		super.onPause();
		mIsFirstCreate = false;
	}
	
	@Override
	protected void onDestroy()
	{
		super.onDestroy();
		
	    SimpleUILauncher.setFolderActiviytHanlder(null);
	    ((LauncherApplication)getApplication()).destroySimpleFolder();
	    
	    mIsFirstCreate = false;
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState)
	{
		outState.putBoolean("SimpleFolder.need_to_be_re-loaded", true);
		super.onSaveInstanceState(outState);
	}
	
	@Override
	protected void onRestoreInstanceState(Bundle state){
		super.onRestoreInstanceState(state);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		super.onBackPressed();
		return true;
		
		//return super.onOptionsItemSelected(item);
	}
	
	@Override
	public void onClick(View v)
	{
		dealTextViewOutLine(v);
		Object tag = v.getTag();
		
		SimpleApplicationInfo app = (SimpleApplicationInfo)tag;
		
		if (app.isNormalHome) // 预留切回标准桌面的应用(暂时不用)
		{
			Handler handler = SimpleUILauncher.getSimpleUILauncherHandler();
			
			if (handler != null){
				handler.sendEmptyMessage(SimpleUILauncher.MSG_CHANGE_TO_NORMAL);
				Log.i(TAG, "onClick change to normal and finish the folder activity");
				finish();
				return;
			}else{
				Log.w(TAG, "getSimpleUILauncherHandler() return null");
				return;
			}
		}
		
		//SimpleUtilities.startActivitySafely(getApplicationContext(), app.intent, tag);
		startActivitySafelyInternal(this, app.intent, tag);
	}
	
	@Override
	public boolean onLongClick(View v)
	{
		Object tag = v.getTag();
		SimpleApplicationInfo app = (SimpleApplicationInfo)tag;
		
		if (!mIsSystemFolder){
			startApplicationUninstallActivity(app);
		}
		
		return true;
	}
	
	public boolean startActivitySafelyInternal(Context context, Intent intent, Object tag)
	{
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		try{
			context.startActivity(intent);
			overridePendingTransition(R.anim.activity_open_enter, R.anim.activity_open_exit);
			return true;
		}catch (ActivityNotFoundException e) {
			Toast.makeText(context, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
	        Log.e(TAG, "Unable to launch. tag=" + tag + " intent=" + intent, e);
		}catch (SecurityException e){
			 Toast.makeText(context, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
	         Log.e(TAG, "Launcher does not have the permission to launch " + intent, e);
		}
		
		return false;
	}
	
	// 卸载应用
	void startApplicationUninstallActivity(SimpleApplicationInfo appInfo) {
    	boolean isDownloadApp = appInfo.isBelongToDownloadFolder(getPackageManager());
        if (!isDownloadApp) {
            int messageId = R.string.uninstall_system_app_text;
            Toast.makeText(this, messageId, Toast.LENGTH_SHORT).show();
        } else {
            String packageName = appInfo.componentName.getPackageName();
            String className = appInfo.componentName.getClassName();
            Intent intent = new Intent(
                    Intent.ACTION_DELETE, Uri.fromParts("package", packageName, className));
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
                    Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
            startActivity(intent);
        }
    }
	
	@Override
	public void layoutNavigationPoint(int paramInt1, int paramInt2, int paramInt3, int paramInt4)
	{
		SimpleCellLayout cellLayout = (SimpleCellLayout)getWorkspace().getChildAt(0);
		int cellLayoutBottom = 0;
		
		if (cellLayout != null)
			cellLayoutBottom = cellLayout.getCellLayoutBottom(false, this);
	    int navHeight = mSimpleQuickNavigation.getMeasuredHeight();
	    
	    int bottomMargin = (paramInt2 - cellLayoutBottom - navHeight) / 2;
	    if (bottomMargin >= 0)
	    	bottomMargin = 0;
	    
	    ((FrameLayout.LayoutParams)mSimpleQuickNavigation.getLayoutParams()).bottomMargin = bottomMargin;
	      mSimpleQuickNavigation.requestLayout();
	}

	@Override
	public void bindAppsChanged()
	{
		removeAndAddApps();
	    refreshNavigationPointLayout();
	}
	
	public void removeAndAddApps()
	{
		Resources res = getResources();
	    int cellWidth = res.getDimensionPixelSize(R.dimen.simple_folder_cell_width);
	    int cellHeight = res.getDimensionPixelSize(R.dimen.simple_folder_cell_height);
	    
	    removeItems();
	    
	    screenCount = mContentApps.size();
	    
	    // 分屏显示,一屏16个应用
	    int append;
	    int pageCount = screenCount/16;
	    if (screenCount % 16 > 0)
	    	append = 1;
	    else 
	    	append = 0;
	    
	    screenCount = pageCount + append;
	    if (screenCount == 0){
	    	return;
	    }
	    
	    // 添加Follder的CellLayout
	    for (int index = 0; index < screenCount; index++)
	    {
	    	SimpleCellLayout cellLayout = (SimpleCellLayout)mInflater.inflate(R.layout.simple_folder_cellllayout, 
	        			mSimpleFolderWorkspace, false);
	        mSimpleFolderWorkspace.addView(cellLayout);
	        
	        ((SimpleCellLayout)mSimpleFolderWorkspace.getChildAt(index)).setCellDimensions(cellWidth, cellHeight, 0, 0);
	    }
	    
	    // 是否显示页面切换指示器
	    if (screenCount <= 1)
	    	mSimpleQuickNavigation.setVisibility(View.GONE);
	    else
	    	mSimpleQuickNavigation.setVisibility(View.VISIBLE);
	    
	    // 文件夹已建立, 往视图中加应用快捷方式
	    if (((LauncherApplication)getApplication()).getSimpleModel().getFolderLoaded()){
	    	addShortcut();
	    }
	}
	
	// 往工作区中添加快捷方式
	private void addShortcut()
	{
		if (mTextView != null && mTextView.getVisibility() != View.GONE)
			mTextView.setVisibility(View.GONE);
		
		for (int i = 0; i < mContentApps.size(); i++)
		{
			SimpleApplicationInfo app = (SimpleApplicationInfo)mContentApps.get(i);
			SimpleBubbleTextView bubbleTextView = createBubbleTextView(R.layout.simple_folder_application,
					(ViewGroup)mSimpleFolderWorkspace.getChildAt(app.screen), app);
			
			if (app.getUnReadNum() > 0){
				bubbleTextView.setUnreadMarkable(true);
				bubbleTextView.setUnreadNum(app.getUnReadNum());
			}
			
			mSimpleFolderWorkspace.addViewInScreen(bubbleTextView, app.screen, app.cellX, app.cellY, 1, 1, true);
		}
	}
	
	// 创建CellLayout中的view
	private SimpleBubbleTextView createBubbleTextView(int resId, ViewGroup viewGroup, SimpleApplicationInfo app){
		LauncherApplication application = (LauncherApplication) getApplication();
		
		SimpleBubbleTextView bubbleTextView = (SimpleBubbleTextView)mInflater.inflate(resId, viewGroup, false);
		bubbleTextView.applyFolderIconFromBubbleTextView(app, application.getSimpleIconCache());
		
		unifyFolderAppTextStyle(bubbleTextView);
		bubbleTextView.setOnClickListener(this);
		
		bubbleTextView.setOnLongClickListener(this);
		
		return bubbleTextView;
	}
	
	// 文件夹中的CellLayout包含的View的文本样式
	private void unifyFolderAppTextStyle(SimpleBubbleTextView bubbleTextView)
	{
		if ("zh".equals(mLocaleLanguage))
		{
			bubbleTextView.setEllipsize(TextUtils.TruncateAt.MARQUEE);
			bubbleTextView.setSingleLine(true);
		}else{
			bubbleTextView.setSingleLine(false);
			bubbleTextView.setEllipsize(TextUtils.TruncateAt.END);
			bubbleTextView.setMaxLines(2);
		}
	}
	
	public void dealTextViewOutLine(View view)
	{
		mClickView = view;
		
		if (view instanceof SimpleBubbleTextView){
			SimpleBubbleTextView bubbleTextView = (SimpleBubbleTextView)view;
			bubbleTextView.setPressed(true);
			bubbleTextView.invalidate();
			mHandler.sendEmptyMessageDelayed(REMOVE_OUT_LINE_MESSAGE, 50);
		}
	}
	
	private void refreshNavigationPointLayout(){
		layoutNavigationPoint(0, getWorkspace().getMeasuredHeight(), 0, 0);
	}
	
	private void removeItems()
	{
		int cellCount = mSimpleFolderWorkspace.getChildCount();
		for (int i = 0; i < cellCount; i++)
			((SimpleCellLayout)mSimpleFolderWorkspace.getChildAt(i)).removeAllViews();
		
		mSimpleFolderWorkspace.removeAllViews();
	}
	
	public void setContentApps()
	{
		if (mIsSystemFolder){
			mContentApps = SimpleLauncherModel.sOtherApps;
		}else{
			mContentApps = SimpleLauncherModel.sDownloadApps;
		}
	}
	
	// 重新加载
	public void reloadApps()
	{
		removeItems();

		screenCount = mContentApps.size();

		int append;
		int pageCount = screenCount / 16;
		if (screenCount % 16 > 0)
			append = 1;
		else
			append = 0;

		screenCount = pageCount + append;

		for (int index = 0; index < screenCount; index++)
		{
			SimpleCellLayout cellLayout = (SimpleCellLayout) mInflater.inflate(R.layout.simple_folder_cellllayout, 
					mSimpleFolderWorkspace, false);
			mSimpleFolderWorkspace.addView(cellLayout);

			((SimpleCellLayout) mSimpleFolderWorkspace.getChildAt(index)).setCellDimensions(160, 240, 0, 0);
		}

		addShortcut();
	}

	public SimpleWorkspace getWorkspace(){
		return mSimpleFolderWorkspace;
	}

	public SimplePageIndicator getSimplePageIndicatior(){
		return mSimpleQuickNavigation;
	}
}
